package cn.lixufeng.org.service.impl;

import cn.lixufeng.basic.service.impl.BaseServiceImpl;
import cn.lixufeng.basic.utils.PageList;
import cn.lixufeng.org.domain.Department;
import cn.lixufeng.org.mapper.DepartmentMapper;
import cn.lixufeng.org.query.DepartmentQuery;
import cn.lixufeng.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS) // 只读不提交事务；有就执行
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void add(Department department) {
        departmentMapper.add(department);
        this.update(department); //
    }

    @Override
    @Transactional
    public void update(Department department) {
        String dirPath = "";    // 需要用到部门层级，先封装
        if(department.getParent() == null){// 如果没有父部门则是增加了顶级部门
            dirPath = "/" + department.getId();
        }else{
            Department parentDept = departmentMapper.findById(department.getParent().getId());
            // dirPath组成是父部门的path加上"/"和自己部门的id
            dirPath = parentDept.getDirPath() + "/"+department.getId();
        }
        department.setDirPath(dirPath);
        departmentMapper.update(department);
    }

    @Override
    public List<Department> findTree() {
        return departmentMapper.findTree();
    }
}
